package com.serverapk.model;

import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2016/6/6.
 */
public class CachedThreadFactory {

    private static CachedThreadFactory cachedThreadFactory;
    private ExecutorService executorService;
    private static final Object o = new Object();

    private HashMap<String, Runnable> runnableHashMap = new HashMap<String, Runnable>();

    private CachedThreadFactory() {
        executorService = Executors.newCachedThreadPool();
    }

    public static CachedThreadFactory getInstance() {
        if (cachedThreadFactory == null) {
            synchronized (o) {
                if (cachedThreadFactory == null) {
                    cachedThreadFactory = new CachedThreadFactory();
                }
            }
        }
        return cachedThreadFactory;
    }

    /**
     * 添加任务
     */
    public void addTask(String TAG, Runnable r) {
        if (runnableHashMap.get(TAG) == null) {
            // 如果无当前TAG线程，则添加线程
            runnableHashMap.put(TAG, r);
            executorService.execute(r);
        } else {
            // 如果有当前TAG线程，则直接返回
            return;
        }
    }

    public void removeTask(String TAG) {
        if (runnableHashMap.get(TAG) == null) {
            return;
        } else {
            synchronized (runnableHashMap.get(TAG)) {
                runnableHashMap.remove(TAG);
            }
            return;
        }
    }

    /**
     * 清除所有任务
     */
    public void clearAllTask() {
        runnableHashMap.clear();
    }

}

